/**
 * Filename: InviteChooseActivity.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/3/3 15:09
 */
package com.github.postsanf.yinian.activity;

import android.content.ContentValues;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.bean.YNAlbum;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.github.postsanf.yinian.fragment.MineFragement;
import com.github.postsanf.yinian.utils.ImageOptHelper;
import com.github.postsanf.yinian.utils.UIHelper;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

public class InviteErWeiMaActivity extends BaseActivity implements View.OnClickListener {
    private String jieTuUrl;
    private File f;
    private String inviteUrl;
    private YNAlbum curAlbum;
    private TextView iv_user_zonename;
    private ImageView iv_showerweima;
    private SimpleDraweeView invite_erweima_face;
    private TextView tv_invite;
    private TextView invite_erweima_save;
    private Bitmap erweimabitmap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yn_activity_invite_erweima);
        curAlbum = YNSingleton.getInstance().getCurAlbum();
        inviteUrl = getIntent().getStringExtra("inviteUrl");
        tv_invite = ((TextView) findViewById(R.id.invite_erweima_share));
        invite_erweima_save = ((TextView) findViewById(R.id.invite_erweima_save));
        tv_invite.setOnClickListener(this);
        invite_erweima_save.setOnClickListener(this);
        findViewById(R.id.iv_back).setOnClickListener(this);
        iv_user_zonename = (TextView) findViewById(R.id.iv_user_zonename);
        iv_user_zonename.setText(curAlbum.getGname());
        iv_showerweima = (ImageView) findViewById(R.id.iv_showerweima);
        invite_erweima_face = (SimpleDraweeView) findViewById(R.id.invite_erweima_face);
        createQRImage(inviteUrl, UIHelper.dip2px(InviteErWeiMaActivity.this, 186), UIHelper.dip2px(InviteErWeiMaActivity.this, 186));
        String urls = (curAlbum == null || curAlbum.getGpic() == null) ? "" : curAlbum.getGpic();
        Uri uri = Uri.parse(urls);
        ImageOptHelper.showFrescoAvatar(uri, invite_erweima_face, InviteErWeiMaActivity.this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.invite_erweima_share:
//                Intent intent = new Intent(InviteErWeiMaActivity.this, PicWallShareActivity.class);
//                intent.putExtra("QRcode", "QRcode");
//                intent.putExtra("UrlShare", inviteUrl);
//                intent.putExtra("firstPic", YNSingleton.getInstance().getCurAlbum().getGpic());
//                intent.putExtra("nickName", application.getCurUser().getUnickname() + "邀请您加入忆年小伙伴私密空间，一起分享照片、记录生活");
//                intent.putExtra("QRtext", "长按识别二维码加入空间");
//                startActivity(intent);
                getUrlBitmap(MineFragement.avatarPic, 1);
                break;
            case R.id.invite_erweima_save:
                DoJieTu();
                break;
        }
    }

    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onResult(SHARE_MEDIA platform) {

            if (platform.name().equals("WEIXIN_FAVORITE")) {
                Toast.makeText(InviteErWeiMaActivity.this, platform + " 收藏成功啦", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(InviteErWeiMaActivity.this, platform + " 分享成功啦", Toast.LENGTH_SHORT).show();
                finish();
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(InviteErWeiMaActivity.this, platform + " 分享失败啦", Toast.LENGTH_SHORT).show();
            if (t != null) {
                com.umeng.socialize.utils.Log.d("yuhao", "throw:" + t.getMessage());
            }
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(InviteErWeiMaActivity.this, platform + " 分享取消了", Toast.LENGTH_SHORT).show();
        }
    };

    Bitmap avatarPicbitmap;

    private void DoJieTu() {
        getUrlBitmap(MineFragement.avatarPic, 2);
    }

    private Bitmap getResPhoto() {
        int width = 750;
        int height = 1334;
        Bitmap result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(result);
        canvas.drawColor(Color.WHITE);
        Rect dst = new Rect();
        dst.left = 175;
        dst.top = 427;
        dst.right = 175 + 400;
        dst.bottom = 427 + 400;
        canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.btn_bg_blue), null, dst, null);
        if (erweimabitmap != null) {
            Rect dst2 = new Rect();
            dst2.left = 203;
            dst2.top = 455;
            dst2.right = 203 + 344;
            dst2.bottom = 455 + 344;
            canvas.drawBitmap(erweimabitmap, null, dst2, null);
        }
        Paint p1 = new Paint();
        p1.setColor(Color.parseColor("#616161"));
        p1.setAntiAlias(true);
        p1.setFilterBitmap(true);
        p1.setTextSize(40f);
        p1.setTextAlign(Paint.Align.CENTER);
        canvas.drawText(application.getCurUser().getUnickname() + " 邀请你加入", 375, 258, p1);
        p1.setColor(Color.parseColor("#033263"));
        p1.setTextSize(44f);
        canvas.drawText(curAlbum.getGname(), 375, 328, p1);
        p1.setTextSize(34f);
        p1.setColor(Color.parseColor("#272727"));
        canvas.drawText("长按识别二维码加入圈子", 375, 955, p1);
        p1.setColor(Color.parseColor("#636363"));
        canvas.drawText("@忆年APP", 375, 1200, p1);
        return result;
    }

    private Bitmap getResPhoto2() {
        int width = 750;
        int height = 1334;
        Bitmap result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(result);
        canvas.drawColor(Color.WHITE);
        Rect rectTop = new Rect();
        rectTop.left = 0;
        rectTop.top = 0;
        rectTop.right = 750;
        rectTop.bottom = 145;
        canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.erweimadraw_top), null, rectTop, null);
        Rect rectButtom = new Rect();
        rectButtom.left = 0;
        rectButtom.top = 1263;
        rectButtom.right = 750;
        rectButtom.bottom = 1334;
        canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.erweimadraw_buttom), null, rectButtom, null);
        Rect rectlogo = new Rect();
        rectlogo.left = 306;
        rectlogo.top = 992;
        rectlogo.right = 306 + 138;
        rectlogo.bottom = 992 + 168;
        canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.erweimadraw_logo), null, rectlogo, null);
        Rect recttip = new Rect();
        recttip.left = 211;
        recttip.top = 856;
        recttip.right = 211 + 328;
        recttip.bottom = 856 + 28;
        canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.erweimadraw_tip), null, recttip, null);
        if (erweimabitmap != null) {
            Rect dst2 = new Rect();
            dst2.left = 190;
            dst2.top = 457;
            dst2.right = 190 + 370;
            dst2.bottom = 457 + 370;
            canvas.drawBitmap(erweimabitmap, null, dst2, null);
        }
        Rect dstava = new Rect();
        dstava.left = 296;
        dstava.top = 70;
        dstava.right = 296 + 158;
        dstava.bottom = 70 + 158;
        canvas.drawBitmap(makeRoundCorner(avatarPicbitmap), null, dstava, null);
        Paint p1 = new Paint();
        p1.setColor(Color.parseColor("#333333"));
        p1.setAntiAlias(true);
        p1.setFilterBitmap(true);
        p1.setTextSize(36f);
        p1.setTextAlign(Paint.Align.CENTER);
        canvas.drawText(application.getCurUser().getUnickname(), 375, 272, p1);
        p1.setColor(Color.parseColor("#999999"));
        p1.setTextSize(30f);
        canvas.drawText("邀请你加入", 375, 272 + 46, p1);
        p1.setColor(Color.parseColor("#333333"));
        p1.setTextSize(36f);
        canvas.drawText(curAlbum.getGname(), 375, 272 + 46 + 30 + 40, p1);
        return result;
    }

    public static Bitmap makeRoundCorner(Bitmap bitmap) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int left = 0, top = 0, right = width, bottom = height;
        float roundPx = height / 2;
        if (width > height) {
            left = (width - height) / 2;
            top = 0;
            right = left + height;
            bottom = height;
        } else if (height > width) {
            left = 0;
            top = (height - width) / 2;
            right = width;
            bottom = top + width;
            roundPx = width / 2;
        }
        Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        int color = 0xff424242;
        Paint paint = new Paint();
        Rect rect = new Rect(left, top, right, bottom);
        RectF rectF = new RectF(rect);
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        return output;
    }


    Handler bitmapHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    Bitmap res1 = getResPhoto();
                    new ShareAction(InviteErWeiMaActivity.this).setPlatform(SHARE_MEDIA.QQ).setCallback(umShareListener)
                            .withMedia(new UMImage(InviteErWeiMaActivity.this, res1))
                            .share();
                    break;
                case 2:
                    Bitmap res2 = getResPhoto2();
                    saveBitmapres(res2);
                    break;
            }
        }
    };

    public void getUrlBitmap(final String url, final int type) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    URL iconUrl = new URL(url);
                    URLConnection conn = iconUrl.openConnection();
                    HttpURLConnection http = (HttpURLConnection) conn;
                    int length = http.getContentLength();
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    BufferedInputStream bis = new BufferedInputStream(is, length);
                    avatarPicbitmap = BitmapFactory.decodeStream(bis);
                    bis.close();
                    is.close();// 关闭流
                    bitmapHandler.sendEmptyMessage(type);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    boolean filebb = false;
    private MediaScannerConnection mMediaonnection;
    String ts;

    public void saveBitmapres(Bitmap bm) {
        filebb = true;
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "yinian/YiNian");
        if (!file.exists()) {
            file.mkdirs();
        }
        ts = "yn_" + System.currentTimeMillis() + ".jpg";
        f = new File(file.getPath() + "/", ts);
        jieTuUrl = f.getAbsolutePath();
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
            Toast.makeText(InviteErWeiMaActivity.this, "已保存", Toast.LENGTH_SHORT).show();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (!f.exists())
            return;
        ContentValues values = new ContentValues(7);
        values.put(MediaStore.Images.Media.TITLE, ts);
        values.put(MediaStore.Images.Media.DISPLAY_NAME, ts);
        values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        values.put(MediaStore.Images.Media.DATA, f.getAbsolutePath());
        getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        // 最后通知图库更新
        try {
            mMediaonnection = new MediaScannerConnection(InviteErWeiMaActivity.this, new MediaScannerConnection.MediaScannerConnectionClient() {
                @Override
                public void onMediaScannerConnected() {
                    mMediaonnection.scanFile(f.getParentFile().getAbsolutePath(), ts);
                }

                @Override
                public void onScanCompleted(String path, Uri uri) {
                    mMediaonnection.disconnect();
                }
            });
            mMediaonnection.connect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    private void getUserTop(int userid) {
//        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
//        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(userid));
//        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynShowUserHead))
//                .setMethod(HttpMethods.Post)
//                .setParamMap(mParam)
//                .setHttpListener(new HttpListener<String>(true, false, true) {
//                    @Override
//                    public void onSuccess(String s, Response<String> response) {
//                        YNLoginResponse resUser = gson.fromJson(s, YNLoginResponse.class);
//                        if (resUser != null && ReqUtils.isSuccess(resUser.getCode()) && resUser.getData().size() > 0) {
//                            YNUser user = resUser.getData().get(0);
////                            Uri avatarUri = Uri.parse(YNUrlHelper.getAvatarUrl(InviteErWeiMaActivity.this, user.getUpic()));
////                            ImageOptHelper.showFrescoAvatar(avatarUri, iv_user_avatar, InviteErWeiMaActivity.this);
//                        }
//                    }
//
//                    @Override
//                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);
//                    }
//                });
//        liteHttp.executeAsync(req);
//    }

    private void createQRImage(String content, int widthPix, int heightPix) {
        try {
            if (content == null || "".equals(content)) {
                return;
            }
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            hints.put(EncodeHintType.MARGIN, 0);
            BitMatrix bitMatrix = updateBit(new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, widthPix, heightPix, hints), 10);
            int width = bitMatrix.getWidth();
            int height = bitMatrix.getHeight();
            int[] pixels = new int[width * height];
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * width + x] = 0xff000000;
                    } else {
                        pixels[y * width + x] = 0xffffffff;
                    }
                }
            }
            erweimabitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            erweimabitmap.setPixels(pixels, 0, width, 0, 0, width, height);
            iv_showerweima.setImageBitmap(erweimabitmap);
        } catch (WriterException e) {
            e.printStackTrace();
        }
    }

    private static BitMatrix updateBit(BitMatrix matrix, int margin) {
        int tempM = margin * 2;
        int[] rec = matrix.getEnclosingRectangle();   //获取二维码图案的属性
        int resWidth = rec[2] + tempM;
        int resHeight = rec[3] + tempM;
        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight); // 按照自定义边框生成新的BitMatrix
        resMatrix.clear();
        for (int i = margin; i < resWidth - margin; i++) {   //循环，将二维码图案绘制到新的bitMatrix中
            for (int j = margin; j < resHeight - margin; j++) {
                if (matrix.get(i - margin + rec[0], j - margin + rec[1])) {
                    resMatrix.set(i, j);
                }
            }
        }
        return resMatrix;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (!filebb && f != null && f.exists()) {
            f.delete();
        }
    }
}



